//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ty.pdm.system.workFlow.listener.common;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.basedrule.dto.TyplmBaseRuleBoundedObjDTO;
import com.hustcad.plm.pdm.basedrule.service.TyplmBasedRuleService;
import com.hustcad.plm.pdm.baseline.module.dto.BaseLineDTO;
import com.hustcad.plm.pdm.baseline.module.dto.TyplmBaseLineMemberAddDTO;
import com.hustcad.plm.pdm.baseline.module.vo.TyplmBaseLineMemberCheckResultVO;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineMemberService;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineService;
import com.hustcad.plm.pdm.container.model.entity.Container;
import com.hustcad.plm.pdm.container.service.ContainerService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.type.model.vo.TypeTree;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CustomListener(
        category = "永续采购BOM校验",
        description = "永续采购BOM校验"
)
public class VerificationLineListener implements ExecutionListener {
    private static final Logger log = LoggerFactory.getLogger(VerificationLineListener.class);
    private static final long serialVersionUID = -9059663559349037414L;
    @CustomListenerField(
            description = "ERP接口编码",
            defaultValue = "",
            required = true
    )
    private FixedValue code;

    @CustomListenerField(
            description = "ERP接口对象",
            defaultValue = "",
            required = true
    )
    private FixedValue erpObject;

    public VerificationLineListener() {

    }

    public void notify(DelegateExecution execution) {
        try {
            log.info("开始执行监听 ==> 物料申请 BaseLineListener");
            String workFlowContainerIdStr = execution.getProcessInstanceBusinessKey();
            BigInteger workFlowContainerId = new BigInteger(workFlowContainerIdStr);
            TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(
                    TyplmWorkFlowContainerService.class);
            if (typlmWorkFlowContainerService != null) {
                WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                        workFlowContainerId);
                if (workFlowContainerView instanceof WorkFlowObjectPackage) {
                    WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
                    if (workFlowObjectPackage.getFlowObjectList() != null && workFlowObjectPackage.getFlowObjectList()
                            .size() != 0) {
                        for (int i = 0; i < workFlowObjectPackage.getFlowObjectList().size(); i++) {
                            FlowObject flowObject = workFlowObjectPackage.getFlowObjectList().get(i);
                            extendedTask(flowObject);
                        }
                    } else {
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("getFlowObjectList为空");
                    }
                }
                else if (workFlowContainerView instanceof FlowChgFormView) {
                    FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
                    if (flowChgFormView.getChgFormVO() != null && flowChgFormView.getChgFormVO()
                            .getEcAffectVOS() != null) {
                        //排除重复的编码
                        Map<String, Object> cmd = new HashMap<>();
                        for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                            ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                            if (cmd.containsKey(ecObjData.getNumber())) {
                                continue;
                            } else {
                                cmd.put(ecObjData.getNumber(), "1");
                            }
                            extendedTaskEco(ecObjData);
                        }
                    }
                }
                else {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("WorkFlowObjectPackage错误");
                }
            } else {
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("TyplmWorkFlowContainerService无法加载");
            }

            log.info("正常执行监听结束 <== 物料申请 BaseLineListener");
        } catch (Exception var5) {
            var5.printStackTrace();
            log.error("监听BaseLineListener异常：" + var5);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(var5.getMessage());
        }
    }

    /**
     * 发部校验处理
     *
     * @param flowObject
     * @return
     */
    public void extendedTask(FlowObject flowObject) {


        TyplmPartService typlmPartService = SpringUtil.getBean(TyplmPartService.class);

        if ("ty.inteplm.part.CTyPart".equals(flowObject.getRefObjectOtype()) == false) {
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(flowObject.getObjectNumber()+" 不是零部件对象");
        }

        BigInteger oid = flowObject.getRefObjectOid();
        String oType = flowObject.getRefObjectOtype();
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        if (typlmPartBomService != null) {
            com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
            expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
            expandBomTreeByFilterDTO.setExpandLevel("1");
            expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
            expandBomTreeByFilterDTO.setIsQueryIBA(true);
            expandBomTreeByFilterDTO.setIsNestedTree(false);

            ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
            childPartsFiltersDTO.setView(partDetailsVO.getView());
            childPartsFiltersDTO.setExpandCondition("latest");
            List<ChildPartsFiltersDTO> list = new ArrayList<>();
            list.add(childPartsFiltersDTO);
            expandBomTreeByFilterDTO.setConditions(list);
            PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                        Boolean.TRUE);
            K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
            Map<String, Object> executionType = k3CloudHttpService.getExecutionType(this.code.getExpressionText(), this.erpObject.getExpressionText());

            List<String> checkErrorList=new ArrayList<>();
            List<String> erpErrorList=new ArrayList<>();
            List<String> checkTypeErrorList=new ArrayList<>();

            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if("c/i".equals(partBomTree.getCheckInOrCheckOut())==false){
                        checkErrorList.add(partBomTree.getObjectNumber());
                    }
                    BigInteger coid = new BigInteger(partBomTree.getPartoid());
                    String coType = partBomTree.getPartotype();
                    PartDetailsVO partDetails = typlmPartService.queryPartDetails(coid, coType);
                    Map<String, List<String>> attrMap=partDetails.getIbaAttributeMap();
                    if(attrMap.containsKey("物料属性")==false){
                        checkTypeErrorList.add(partBomTree.getObjectNumber());
                    }
                    else{
                        List<String> attr=attrMap.get("物料属性");
                        if("1".equals(attr.get(0))==false && "3".equals(attr.get(0))==false){
                            checkTypeErrorList.add(partBomTree.getObjectNumber());
                        }
                    }

                    try {
                        String erpId=getErpMaterials(partBomTree.getObjectNumber(),executionType);
                        if(erpId==null){
                            erpErrorList.add(partBomTree.getObjectNumber());
                        }
                    } catch (Exception e) {
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("查询ERP接口错误，可能的原因：1）PLM中配置的账户密码失效；2）PLM服务器与ERP服务器网络中断。请联系公司IT管理员排查。");

                    }
                }
            }

            if(checkErrorList.size()>0 && checkErrorList.size()>0 && checkTypeErrorList.size()>0){
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList)+" 零部件对象ERP没有数据"+ JSONObject.toJSONString(erpErrorList)
                                                                                       +" 零部件对象不是外购属性"+ JSONObject.toJSONString(checkTypeErrorList));
            }
            else{
                if(checkErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList));
                }
                if(checkTypeErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象不是外购属性"+ JSONObject.toJSONString(checkTypeErrorList));
                }
                if(erpErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象ERP没有数据"+ JSONObject.toJSONString(erpErrorList));
                }

            }

        }
    }

    /**
     * 变更校验处理
     *
     * @param ecObjData
     * @return
     */
    public void extendedTaskEco(ECObjData ecObjData) {

        TyplmBaseLineMemberService typlmBaseLineMemberService = SpringUtil.getBean(TyplmBaseLineMemberService.class);
        TyplmBaseLineService typlmBaseLineService = SpringUtil.getBean(TyplmBaseLineService.class);
        TyplmPartService typlmPartService = (TyplmPartService) SpringUtil.getBean(
                TyplmPartService.class);
        if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype()) == false) {
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(ecObjData.getObjectNumber()+" 不是零部件对象");
        }

        BigInteger oid = ecObjData.getRefObjectOid();
        String oType = ecObjData.getRefObjectOtype();
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        if (typlmPartBomService != null) {
            com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
            expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

            ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
            childPartsFiltersDTO.setBaseLineOid("");
            childPartsFiltersDTO.setDate("");
            childPartsFiltersDTO.setExpandCondition("latest");
            childPartsFiltersDTO.setLifecycleStateKey("");
            childPartsFiltersDTO.setPurposeOfBom("");
            childPartsFiltersDTO.setSpareBom("");
            childPartsFiltersDTO.setView(partDetailsVO.getView());
            List<ChildPartsFiltersDTO> list = new ArrayList<>();
            list.add(childPartsFiltersDTO);
            expandBomTreeByFilterDTO.setConditions(list);

            expandBomTreeByFilterDTO.setExpandLevel("N");
            expandBomTreeByFilterDTO.setFatherNumber(partDetailsVO.getObjectNumber());
            expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
            expandBomTreeByFilterDTO.setFatherOtype(partDetailsVO.getOtype());
            expandBomTreeByFilterDTO.setFilterMode("0");
            expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
            expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
            expandBomTreeByFilterDTO.setIsApplyRoot(false);
            expandBomTreeByFilterDTO.setIsFilterAttr(false);
            expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
            expandBomTreeByFilterDTO.setIsNestedTree(false);
            expandBomTreeByFilterDTO.setIsQueryIBA(true);

            PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                        Boolean.TRUE);

            K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
            Map<String, Object> executionType = k3CloudHttpService.getExecutionType(this.code.getExpressionText(), this.erpObject.getExpressionText());

            List<String> checkErrorList=new ArrayList<>();
            List<String> erpErrorList=new ArrayList<>();

            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if("c/i".equals(partBomTree.getCheckInOrCheckOut())==false){
                        checkErrorList.add(partBomTree.getObjectNumber());
                    }
                    try {
                        String erpId=getErpMaterials(partBomTree.getObjectNumber(),executionType);
                        if(erpId==null){
                            erpErrorList.add(partBomTree.getObjectNumber());
                        }
                    } catch (Exception e) {
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("查询ERP接口错误");

                    }
                }
            }

            if(checkErrorList.size()>0 && checkErrorList.size()>0){
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList)+" 零部件对象ERP没有数据"+ JSONObject.toJSONString(erpErrorList));
            }
            else{
                if(checkErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象被检出或锁定"+ JSONObject.toJSONString(checkErrorList));
                }
                if(erpErrorList.size()>0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("零部件对象ERP没有数据"+ JSONObject.toJSONString(erpErrorList));
                }
            }
        }



    }

    /**
     * 查询ERP物料信息
     * @param number
     * @param executionType
     * @return
     * @throws Exception
     */
    public String getErpMaterials(String number, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        SendErpDataUtils.init();

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("CreateOrgId", 0);
        outMap.put("Id", "");
        outMap.put("IsSortBySeq", false);
        outMap.put("Number",number);

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);

        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "BD_MATERIAL");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud//Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        //20251009解决bug，静态对象必须先初始化
                        SendErpDataUtils.init();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }
            if (httpResult != null) {
                JSONObject Result=httpResult.getJSONObject("Result");
                JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus");
                if(ResponseStatus.getBooleanValue("IsSuccess")==true){
                    JSONObject ResultUser=Result.getJSONObject("Result");
                    return ResultUser.getString("Number");
                }
            }
        }
        return null;
    }
}
